package com.fingard.dsp.bank.directbank.ccb02;

import java.io.File;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptData;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptDataHelper;
import com.fingard.dsp.bank.directConfig.ReceiptProConfig;
import com.fingard.dsp.bank.directbank.bankInterface.IReceiptPro;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.dsp.task.command.SyncReceipt;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class CCB02ReceiptPro extends CCB02Base implements IReceiptPro{

	public RetAtsReceipt qryReceiptOneDay(ReceiptProConfig pConfig, ReqQryReceipt pReqReceipt, Date pOneDay)
			throws Exception {
		int intPageNumber = 1;//页码数 默认查询第一页
        boolean tmpQryNext = true;//异常标志 false表示异常
        boolean tmpPageNext = true;//是否最后一页标志 false表示最后一页
        int pageSize = getBankConfig().getValueAsInt("pageSize", 20, "receipt");
        //当1.1接口异常或1.1接口查询到最后一页时跳出循环
        String qryDay8 = Format.Date8Format.format(pOneDay);
        ReceiptDataHelper receiptHelper = null;//回单数据保存类，分区分表
        try{
        	receiptHelper = new ReceiptDataHelper(pReqReceipt.reqHeader.tenant, pOneDay);
        	String aLog = "";
        	try{
        		while (tmpQryNext && tmpPageNext) {
                	//1.1 外联电子回单信息查询
                    //赋值通用参数
                    CCB02Header header = new CCB02Header();
                    header.REQUEST_SN = this.getQryTransID();//p_reqReceipt.reqHeader.transSeqID;
                    header.TX_CODE = "NWHD01";//交易码
                    XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                    //写入通用的头部节点
                    writeCommonHeader(xmlWriter, header);
                    xmlWriter.writeStartElement("TX_INFO");
                    xmlWriter.writeElementString("ACC_NO", pReqReceipt.actNum);
                    xmlWriter.writeElementString("STARTDATE", qryDay8);
                    xmlWriter.writeElementString("ENDDATE", qryDay8);
                    xmlWriter.writeElementString("PAGE", String.valueOf(intPageNumber));
                    xmlWriter.writeElementString("TOTAL_RECORD", String.valueOf(pageSize));
                    xmlWriter.writeEndElement();
                    xmlWriter.writeEndDocument();
                    aLog = "PAGE:"+intPageNumber;
                    WriteBankLogLn(aLog);
                    String[] tmpStrReq = sendToBank(xmlWriter.toXmlString());

                    if (tmpStrReq[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrReq[1], tmpSbMsg);
                        if (tmpBkReader != null) {
                            String return_code = tmpBkReader.getFirstText("/TX/RETURN_CODE");//返回码
                            String return_msg = tmpBkReader.getFirstText("/TX/RETURN_MSG");//返回码说明
                            if ("000000".equals(return_code)) {
                                //比较当前页与总页数，判断是否进行下一页操作
                                String page = tmpBkReader.getFirstText("/TX/TX_INFO/PAGE");//当前页
                                String total_page = tmpBkReader.getFirstText("/TX/TX_INFO/TOTAL_PAGE");//总页数
                                if ("0".equals(page) || "0".equals(total_page)) {
                                    tmpQryNext = false;
                                    WriteBankLogLn("外联电子回单信息查询--响应页面为空");
                                    continue;
                                }
                                if (Integer.parseInt(page) == Integer.parseInt(total_page)) {
                                    //当前页=总页数，最后一次循环
                                    tmpPageNext = false;
                                } else {
                                    intPageNumber = Integer.parseInt(page) + 1;
                                }
                                //待下载回单编号
                                //StringBuilder download_nos = new StringBuilder();
                                //循环获取回单编号、获取返回回单信息
                                while (tmpBkReader.read("/TX/TX_INFO/DETAILLIST")) {
                                	ReceiptData rcpt = new ReceiptData();
                                	rcpt.ownAct = pReqReceipt.actNum;
                                	rcpt.bank = "105";
                                	rcpt.srcSys = this.bankFront.bankCode;;
                                	rcpt.istNbr = tmpBkReader.readedXElement.getSingleText("INNER_NO");
                                	rcpt.receiptNo = tmpBkReader.readedXElement.getSingleText("LOG_NO");
                                	rcpt.bnkSeqNo = rcpt.receiptNo;
                                	rcpt.busDate = Integer.parseInt(qryDay8);
                                	String TRAN_DATE = tmpBkReader.readedXElement.getSingleText("TRAN_DATE");//交易日期
                                	if(!qryDay8.equals(TRAN_DATE)){
                                		aLog = rcpt.receiptNo+"回单数据的日期"+TRAN_DATE+"与预期"+qryDay8+"不符";
                                		WriteBankLogLn(aLog);
                                		FGBiz.logTrace.error(this.getLogCode(), aLog);
                                	}
                                	/*
                                	if(CCBS_TxnSrlNos.containsKey(rcpt.receiptNo)){
                                		rcpt.busRef = CCBS_TxnSrlNos.get(rcpt.receiptNo);
                                	}*/
                                    String CR_COD = tmpBkReader.readedXElement.getSingleText("CR_COD");
                                    if("贷".equals(CR_COD)){
                                    	rcpt.moneyWay = "2";
                                    }else if("借".equals(CR_COD)){
                                    	rcpt.moneyWay = "1";
                                    }
                                    rcpt.amount = new BigDecimal(tmpBkReader.readedXElement.getSingleText("TX_AMT"));
                                    rcpt.receiptType = getBankConfig().getMapValueByKey("receiptTypeMapping", tmpBkReader.readedXElement.getSingleText("DOC_TYP"));
                                    rcpt.voucherNo = tmpBkReader.readedXElement.getSingleText("DOC_NO");
                                    rcpt.oppActNum = tmpBkReader.readedXElement.getSingleText("OP_ACCT_NO");
                                    rcpt.oppActName = tmpBkReader.readedXElement.getSingleText("OP_ACCT_NAME");
                                    rcpt.cur = convertCurToATS(tmpBkReader.readedXElement.getSingleText("CURR_NAME"));
                                    if(StringHelper.isNullOrEmpty(rcpt.cur)){
                                    	rcpt.cur = convertCurToATS(tmpBkReader.readedXElement.getSingleText("CCYCD"));//币种
                                    }
                                    int inRe = receiptHelper.insertIfNotExist(rcpt);
                                    if(inRe == 0 && StringHelper.hasAnyChar(rcpt.busRef)){
                                    	//由于建行历史明细可能返回的节点不对称，造成busRef为空，这里再补更新一次
                                    	int upAff = receiptHelper.updateBusRef(rcpt);
                                    	WriteBankLogLn(rcpt.receiptNo+"更新BusRef，影响行数："+upAff);
                                    }
                                    WriteBankLogLn(rcpt.receiptNo+"写入数据库，影响行数："+inRe);
                                }
                            } else {
                                tmpQryNext = false;
                                WriteBankLogLn(return_msg);
                                continue;
                            }
                        } else {
                            tmpQryNext = false;
                            WriteBankLogLn(tmpSbMsg.toString());
                        }
                    } else {
                        tmpQryNext = false;
                        WriteBankLogLn(tmpStrReq[1]);
                    }
                }
        	}catch(Exception ex){
        		WriteBankLogLn(ex);
        		FGBiz.logTrace.exception(this.getLogCode(), ex);
        	}
        	aLog = pReqReceipt.actNum+"，"+qryDay8+"回单数据查询完成，开始下载文件";
            WriteBankLogLn(aLog);
            FGBiz.logTrace.debug(this.getLogCode(), aLog);
            ArrayList<String> list = receiptHelper.getIstNbrList(pReqReceipt.actNum, pOneDay);
            aLog = pReqReceipt.actNum+"，"+qryDay8+"需要进行下载的回单文件个数："+list.size();
            WriteBankLogLn(aLog);
            FGBiz.logTrace.debug(this.getLogCode(), aLog);
            if(list.size() <= 0){
                return null;
            }
            for(int i=0;i<list.size();i++){
            	String istNbr = list.get(i);
            	aLog = pReqReceipt.actNum+"，"+qryDay8+"下载"+istNbr;
                WriteBankLogLn(aLog);
                FGBiz.logTrace.debug(this.getLogCode(), aLog);
              //begin
                //1.2 外联单笔回单文件查询
                String fileName = "";
                //赋值通用参数
                CCB02Header header1 = new CCB02Header();
                header1.REQUEST_SN = this.getQryTransID();
                header1.TX_CODE = "NWHD02";
                XmlTextWriter queryXmlWriter = new XmlTextWriter();//发银行报文的XML对象
                //写入通用的头部节点
                writeCommonHeader(queryXmlWriter, header1);
                queryXmlWriter.writeStartElement("TX_INFO");
                queryXmlWriter.writeElementString("ACC_NO", pReqReceipt.actNum);//帐号
                queryXmlWriter.writeElementString("DOWNLOAD_NOS", istNbr);//待下载的回单编号
                //queryXmlWriter.writeElementString("TRAN_DATE", tranDate);//交易日期
                queryXmlWriter.writeEndElement();
                queryXmlWriter.writeEndDocument();

                //发送外联单笔回单文件查询
                String[] tmpStrReq2 = sendToBank(queryXmlWriter.toXmlString());

                if (tmpStrReq2[0].length() == 0) {
                    StringBuilder tmpSbMsg2 = new StringBuilder();
                    XmlTextReader tmpBkReader2 = loadBankRespXmlReader(tmpStrReq2[1], tmpSbMsg2);
                    if (tmpBkReader2 != null) {
                        String returnCode = tmpBkReader2.getFirstText("/TX/RETURN_CODE");//返回码
                        String returnMsg = tmpBkReader2.getFirstText("/TX/RETURN_MSG");//返回码说明
                        if ("000000".equals(returnCode)) {
                            String fileSuccess = tmpBkReader2.getFirstText("/TX/TX_INFO/FILE_SUCCESS");//文件发送成功标志
                            if ("0".equals(fileSuccess)) {
                                fileName = tmpBkReader2.getFirstText("/TX/TX_INFO/FILE_NAME");//文件名
                            } else {
                                WriteBankLogLn("外联批量回单文件查询--文件发送失败");
                                continue;
                            }
                        } else {
                            WriteBankLogLn(returnMsg);
                            continue;
                        }
                    } else {
                        WriteBankLogLn(tmpSbMsg2.toString());
                        continue;
                    }
                } else {
                    WriteBankLogLn(tmpStrReq2[1]);
                    continue;
                }
                //1.3 文件下载
                if ("".equals(fileName) || fileName == null) {
                    WriteBankLogLn("外联批量回单文件查询--响应文件名为空");
                    continue;
                }
                //赋值通用参数
                CCB02Header header3 = new CCB02Header();
                header3.REQUEST_SN = this.getQryTransID();
                header3.TX_CODE = "6W0111";
                XmlTextWriter downXmlWriter = new XmlTextWriter();//发银行报文的XML对象
                //写入通用的头部节点
                writeCommonHeader(downXmlWriter, header3);
                downXmlWriter.writeStartElement("TX_INFO");
                downXmlWriter.writeElementString("SOURCE", fileName);
                downXmlWriter.writeElementString("FILEPATH", "CCMSHD");
                downXmlWriter.writeElementString("LOCAL_REMOTE", "0");
                downXmlWriter.writeEndElement();
                downXmlWriter.writeEndDocument();

                //发送文件下载请求报文
                String[] tmpStrReq3 = sendToBank(downXmlWriter.toXmlString());

                if (tmpStrReq3[0].length() == 0) {
                    StringBuilder tmpSbMsg3 = new StringBuilder();
                    XmlTextReader tmpBkReader3 = loadBankRespXmlReader(tmpStrReq3[1], tmpSbMsg3);
                    if (tmpBkReader3 != null) {
                        String downReturnCode = tmpBkReader3.getFirstText("/TX/RETURN_CODE");//返回码
                        String downReturnMsg = tmpBkReader3.getFirstText("/TX/RETURN_MSG");//返回码说明
                        if ("000000".equals(downReturnCode)) {
                        	
                            //下载成功，取目录对应文件
                            String downloadPath = StringHelper.trimEndFileSp(bankFront.bankReceiptMainDir) + File.separator + StringHelper.trimStartFileSp(fileName);
                            File downFile = new File(downloadPath);
                            if(!downFile.exists()){
                            	WriteBankLogLn("不存在回单文件:" + downloadPath+"请检查bankFront.bankReceiptMainDir配置是否正确");
                                continue;
                            }
                            
                            String localPath = pConfig.getRelativeSaveDir(pReqReceipt.reqHeader, pOneDay) + File.separator + pReqReceipt.actNum;
                            if(!fileName.contains(qryDay8)){
                            	localPath+=File.separator+qryDay8;
                            }
                            String localFileRelative = localPath + File.separator + StringHelper.trimStartFileSp(fileName);
                            localFileRelative = StringHelper.replaceFileSp(localFileRelative);
                            String localPdfFilePath = pConfig.localSaveMainDir+File.separator+localFileRelative;
                            
                            if(FileHelper.copyFileWithCompare(downFile, localPdfFilePath)){
                            	int rowAff = receiptHelper.updateDownState(pReqReceipt.actNum, istNbr,localFileRelative, fileName, "2");
                                aLog = "回单编号"+istNbr+"，文件"+fileName+"下载成功，更新影响行数："+rowAff;
                                WriteBankLogLn(aLog);
                                FGBiz.logTrace.debug(this.getLogCode(), aLog);
                            }else{
                            	aLog = "回单编号"+istNbr+"，文件"+fileName+"下载失败";
                    			WriteBankLogLn(aLog);
                                FGBiz.logTrace.error(this.getLogCode(), aLog);
                            }
                            
                        } else {
                            WriteBankLogLn(downReturnMsg);
                            continue;
                        }
                    } else {
                        WriteBankLogLn(tmpSbMsg3.toString());
                        continue;
                    }
                } else {
                    WriteBankLogLn(tmpStrReq3[1]);
                    continue;
                }
            	//end
            }
            SyncReceipt.resetDelayCounter();//同步任务重新计数延时
        }catch(Exception ex){
        	this.WriteBankLogLn(ex);
        }finally{
        	receiptHelper.close();
        }
		return null;
	}

}
